package com.googlecode.layout4j.parser;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.googlecode.layout4j.domain.SimpleContentRef;

/**
 * Handles some of the fluff around SAX parsing.
 * @author Matt Humphreys
 */
public class ContentExtractor {
	private static Logger log = LoggerFactory.getLogger(ContentExtractor.class);
//	// Doctype is just used for resolving entities
//	static final String XML_FURNITURE_START = "<?xml version='1.0' encoding='UTF-8'?>"
//			+ "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"xhtml1-transitional.dtd\">"
//			+ "<root xmlns:cms='http://www.yojava.org/cms'>";
//	static final String XML_FURNITURE_END = "</root>";
	
//	private static Reader initSaxReader(String layout, boolean addXmlFurniture) {
//		if (addXmlFurniture) {
//			return new StringReader(XML_FURNITURE_START + layout + XML_FURNITURE_END);
//		} else {
//			return new StringReader(layout);
//		}
//	}
	
	public static List<SimpleContentRef> extractContent(String layout) throws LayoutException {
		ContextExtractorHandler handler = new ContextExtractorHandler();
		extractContent(layout, handler);
		return handler.getContentList();
	}
	
	public static void extractContent(String layout, DefaultHandler handler) 
			throws LayoutException {
		Reader saxReader = new StringReader(layout);//initSaxReader(layout, addXmlFurniture);
		javax.xml.parsers.SAXParserFactory spf = SAXParserFactory.newInstance();
	    spf.setValidating(false); // No validation required
		try {
			javax.xml.parsers.SAXParser parser = spf.newSAXParser();
			org.xml.sax.InputSource input = new InputSource(saxReader);
			
			// Give the InputSource an absolute URL for the file, so that
		    // it can resolve relative URLs in a <!DOCTYPE> declaration
			//input.setSystemId(systemId);
		    parser.parse(input, handler);
		} catch (IOException ex) {
			throw new LayoutException(ex);
		} catch (ParserConfigurationException ex) {
			throw new LayoutException(ex);
		} catch (SAXException ex) {
			throw new LayoutException(ex);
		}
		// XXX: This should be streamed e.g. http://ostermiller.org/convert_java_writer_reader.html
	}
	
}
